package top.oneit.jdownload.utils;


import okhttp3.*;
import top.oneit.jdownload.config.AddChrome95RequestHeadersInterceptor;
import top.oneit.jdownload.constants.RequestMethod;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author lingkang
 */
public class HttpUtils {
    private static OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(20, TimeUnit.SECONDS) //连接超时
//            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS) //读取超时
//            .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS) //写超时
            .addInterceptor(new AddChrome95RequestHeadersInterceptor())
            .build();

    public static Headers getHeader(String url, RequestMethod method, Map<String, String> head, String bodyStr) throws Exception {
        return getHeader(url, method, head, bodyStr, null);
    }

    public static Headers getHeader(String url, RequestMethod method, Map<String, String> head, String bodyStr, String bodyType) throws Exception {
        Response response = client.newCall(getRequest(url, method, head, bodyStr, null)).execute();
        if (response.code() == 404) {
            throw new Exception("资源未找到404！");
        }
        return response.headers();
    }

    /**
     * 封装请求参数到  Request
     */
    public static Request getRequest(String url, RequestMethod method, Map<String, String> head, String bodyStr, String bodyType) {
        Request.Builder builder = new Request.Builder();
        builder = builder.url(url);
        if (method != null) {
            if ("post".equals(method.toString().toLowerCase())) {
                if (bodyType == null) {
                    bodyType = "application/json";
                }
                RequestBody body = RequestBody.create(MediaType.parse(bodyType), bodyStr);
                builder = builder.post(body);
            } else if ("head".equals(method.toString().toLowerCase())) {
                builder.method("HEAD", null);
            }
        }
        if (head != null && !head.isEmpty()) {
            for (Map.Entry<String, String> map : head.entrySet()) {
                builder.addHeader(map.getKey(), map.getValue());
            }
        }
        return builder.build();
    }

}
